package com.easy.project.base.exception;

import cn.dev33.satoken.exception.NotLoginException;
import com.easy.project.base.result.BizResult;
import com.easy.project.base.result.SystemErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.Objects;

/**
 * 全局异常处理
 * @author wxz
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<BizResult<?>> globalExceptionHandler(Exception ex) {
        log.error("Exception: ", ex);
        // 业务异常
        if (ex instanceof ServiceException){
            return ResponseEntity.status(HttpStatus.OK).body(BizResult.error((ServiceException)ex));
        }
        // 参数验证失败
        if (ex instanceof BindException){
            BindException bindException = (BindException) ex;
            return ResponseEntity.status(HttpStatus.OK).body(BizResult.error(SystemErrorCodeEnum.ARGUMENT_VALID_ERROR.getCode(), Objects.requireNonNull(bindException.getFieldError()).getDefaultMessage()));
        }
        // 文件上传大小超过了限制
        if (ex instanceof MaxUploadSizeExceededException){
            return ResponseEntity.status(HttpStatus.OK).body(BizResult.error(SystemErrorCodeEnum.FILE_MAX_ERROR));
        }
        // token 失效
        if (ex instanceof NotLoginException){
            return ResponseEntity.status(HttpStatus.OK).body(BizResult.error(SystemErrorCodeEnum.TOKEN_ERROR));
        }
        return ResponseEntity.status(HttpStatus.OK).body(BizResult.error(SystemErrorCodeEnum.ERROR));
    }

}
